// base
import Taro, { Component } from '@tarojs/taro'
import { View, Image } from '@tarojs/components'
import { AtActionSheet } from 'taro-ui'
// redux
import { connect } from '@tarojs/redux'
import { DOREQUESTMYALBUM } from './store/actions/pagemyalbum'
import { UPDATEPAGEMYALBUM } from './store/types/pagemyalbum'
// less
import './index.less'

// componnet
import { previewImage } from '../../crossplatform/apiservice/media/imageView'
import If from '../../components/page-components/if'
import scaleImageSrc from '../../util/pagemethods/scaleImageSrc'
import { dealImgUrl } from '../../configuration/staticimg'
import { delImgRequest, insertImgRequest } from '../../service/user-archive-controller'
import { showToast } from '../../crossplatform/apiservice/toast'
import Dialog from '../../components/page-components/dialog'
import { doUpload } from '../../util/pagemethods/upload'

const mapActiontoProps = dispatch => ({
  updateState (payload) {
    dispatch({
      type: UPDATEPAGEMYALBUM,
      payload: {
        ...payload
      }
    })
  },
  dorequest (payload) {
    return new Promise(resolve => {
      let promise = DOREQUESTMYALBUM(payload)
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  }
})

@connect(
  ({ pagemyalbum, userinfo }) => ({
    ...pagemyalbum,
    userId: userinfo.userId
  }),
  mapActiontoProps
)
class MyAlbum extends Component {
  config = {
    navigationBarTitleText: '我的相册'
  }
  static defaultProps = {
    elegantDemeanour: []
  }
  constructor (props) {
    super(props)
    this.state = {
      bottomVisible: false,
      modalVisible: false
    }
  }

  componentWillMount () {
    // onLoad
    this.queryWrap()
  }

  componentDidMount () {
    // onready
  }

  componentDidShow () {
    // onshow
  }

  componentDidHide () {
    // onhide
  }

  componentWillUnmount () {
    // onUnload
  }

  queryWrap = () => {
    const { userId } = this.props
    this.props.dorequest({ userId })
  }

  onSetting = () => {
    // 点击管理
    const { bottomVisible } = this.state
    this.setState({
      bottomVisible: !bottomVisible
    })
  }

  onTap = () => {
    // 点击上传图片
    doUpload('avatar').then(({ status, url }) => {
      if (status) {
        this.insertImg(url)
      } else {
        showToast({
          title: '上传失败'
        })
      }
    })
  }

  insertImg = imageUrl => {
    let userId = this.props.userId
    insertImgRequest({ userId, imgUrl: imageUrl }).then(({ data }) => {
      this.queryWrap()
    })
  }

  onCheckAll = () => {
    // 点击全选
    let { elegantDemeanour } = this.props
    const checkCount = elegantDemeanour.filter(e => e.checked).length
    elegantDemeanour = elegantDemeanour.map(e => ({
      ...e,
      checked: checkCount !== elegantDemeanour.length
    }))
    this.props.updateState({
      elegantDemeanour
    })
  }

  clickImg = event => {
    // 点击图片选择
    const index = event.currentTarget.dataset.index
    const { bottomVisible } = this.state
    const { elegantDemeanour } = this.props
    if (bottomVisible) {
      this.props.updateState({
        elegantDemeanour: elegantDemeanour.map((e, i) =>
          i === index
            ? {
              ...e,
              checked: !e.checked
            }
            : e
        )
      })
    } else {
      previewImage({
        current: dealImgUrl(elegantDemeanour[index].pic),
        urls: elegantDemeanour.map(e => dealImgUrl(e.pic))
      })
    }
  }

  onDelete = () => {
    // 点击删除 显示弹窗
    this.setState({
      modalVisible: true
    })
  }

  onDeleteOk = () => {
    const { elegantDemeanour } = this.props
    const checkedImgArr = elegantDemeanour.filter(e => e.checked).map(e => e.id)
    delImgRequest({ ids: checkedImgArr }).then(({ data }) => {
      if (data.status) {
        showToast({
          title: '删除成功！'
        })
        this.queryWrap()
        this.setState({
          bottomVisible: false,
          modalVisible: false
        })
      } else {
        showToast({
          title: '删除失败！'
        })
      }
    })
  }

  onDeleteCancel = () => {
    // 取消删除
    this.setState({
      modalVisible: false
    })
  }

  render () {
    const { bottomVisible, modalVisible } = this.state
    const { elegantDemeanour = [] } = this.props
    const checkAll = elegantDemeanour.every(e => e.checked)
    return (
      <View className="MyAlbum_id79306">
        <View className="top">
          <View className="title">我的相册</View>
          <View className="btn" onClick={this.onSetting}>
            {!bottomVisible ? '管理' : '取消'}
          </View>
        </View>
        <If visible={!bottomVisible}>
          <View className="upload-btn" onTap={this.onTap}>
            <Image
              className="iconimg"
              src="https://imagesize.hrwork.com/sp/files/da8795ff-522b-4c3a-ac2d-08b15db85716.png"
            />
            <View className="upload-text">上传照片</View>
          </View>
        </If>
        <View className="pic-container">
          {elegantDemeanour.map((item, index) => {
            return (
              <View className="pic-item" key={item.pic} data-index={index} onClick={this.clickImg}>
                <Image className="pic-img" mode="aspectFill" src={scaleImageSrc(item.pic)} />
                <Image
                  className={`check-status ${item.checked && bottomVisible ? '' : 'hide'}`}
                  src="https://imagesize.hrwork.com/sp/files/5f5130a2-c900-42a6-ba80-aab3b01770a1.png"
                />
              </View>
            )
          })}
        </View>

        <If visible={bottomVisible}>
          <View className="bottom-btn">
            <View className="bottom-left" onClick={this.onCheckAll}>
              <If visible={checkAll} renderElse={<View className="no-check" />}>
                <Image
                  src="https://imagesize.hrwork.com/sp/files/5f5130a2-c900-42a6-ba80-aab3b01770a1.png"
                  className="bottom-img"
                />
              </If>
              <View className="left-text">{checkAll ? '取消全选' : '全选'}</View>
            </View>
            <View className="bottom-right" onClick={this.onDelete}>
              删除
            </View>
          </View>
        </If>
        <AtActionSheet isOpened={modalVisible}>
          <Dialog
            title="提醒"
            subtext="确定要删除所选照片吗？"
            leftText="取消"
            rightText="删除"
            onOk={this.onDeleteOk}
            onLeftOk={this.onDeleteCancel}
          />
        </AtActionSheet>
      </View>
    )
  }
}

export default MyAlbum
